package com.hp.bon.sgw.wh.channel.handler;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.hp.bon.sgw.Constants;
import com.hp.bon.sgw.Constants.MessageType;
import com.hp.bon.sgw.bean.XmlMessage;
import com.hp.bon.sgw.core.BuzProcessorManager;
import com.hp.bon.sgw.core.CallParam;
import com.hp.bon.sgw.core.channel.SoapChannel;
import com.hp.bon.sgw.core.channel.handler.IAsynCallHandler;
import com.hp.bon.sgw.domain.MessageDetail;
import com.hp.bon.sgw.threads.MessageDetailCacheManager;
import com.hp.bon.sgw.threads.TaskManager;
import com.hp.ocs.diameter.message.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: HBCFQHandle
 * @Description: 橙分期费用查询
 * @author: fengr
 * @date:2019年6月26日 上午11:59:30
 */
public class HBCFQHandle2 implements IAsynCallHandler {
	private static final Logger _log = LoggerFactory.getLogger(HBCFQHandle2.class);

	private PrintStream printStream;
	private JSONObject requestObject;

	public HBCFQHandle2(PrintStream printStream, JSONObject requestObject) {
		this.printStream = printStream;
		this.requestObject = requestObject;
	}

	@Override
	public int getProtocolType() {
		return 0;
	}

	@Override
	public void onCallResult(CallParam callParam) {
		XmlMessage ack = null;
		Object response = null;
		if (callParam.getResponse() != null) {
			response = callParam.getResponse();
		} else if (callParam.getRecvResponse() != null) {
			response = callParam.getRecvResponse();
		}
		if (response == null) {
			////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
			int _retcodeTmp = callParam.getRetCode() == 3002 ? 11202 : callParam.getRetCode();
			ack = SoapChannel.createERRAnwser(callParam.getSessionId(), _retcodeTmp, callParam.getResultMsg());
			callParam.setServiceResultCode(_retcodeTmp);// 11203
		} else {
			if (response instanceof Message) {// CCA -> XML
				ack = BuzProcessorManager.getInstance().convertMessageToAck(callParam);
			} else if (response instanceof XmlMessage) {
				ack = (XmlMessage) response;
			} else {
				_log.warn("unknown response type2:" + callParam.getResponse().getClass().getName());
			}
		}
		try {
			if (response instanceof Message) {
				
			}else if (response instanceof XmlMessage) {
				XmlMessage xmlMessage=(XmlMessage) response;
//				String data = xmlMessage.getDATA();
//				String rc = xmlMessage.getRC();
//				int reptag = xmlMessage.getREPTAG();
//				String rsv1 = xmlMessage.getRSV1();
//				String rsv2 = xmlMessage.getRSV2();
//				String rtt = xmlMessage.getRTT();
//				_log.info("getResponse:XmlMessage:data{"+data+"},rc{"+rc+"},reptag{"+reptag+"},v1{"+rsv1+"},v2{"+rsv2+"},rtt{"+rtt+"}");
			}
			String respXML = convertResponseString( response, callParam.getServiceResultCode());
			byte[] resp = respXML.getBytes("UTF-8");
			ack.setLength(resp.length);
			ack.setMsgTime(System.currentTimeMillis());
			printStream.write(resp);
			printStream.close();
			callParam.setResponse(ack);
			if (callParam.getRetCode() == Constants.ResultCode.SUCCESS) {// 成功的消息，请求应答入库
				MessageDetail detail = new MessageDetail();
				detail.setBusinessCallId(callParam.getBussinessCallId());
				detail.setSessionId(callParam.getSessionId());
				detail.setServiceContextId(callParam.getServiceContextId());
				detail.setMessageType(MessageType.WSA);
				detail.setDetails(ack.getDATA());
				detail.setMsgTime(new Date(ack.getMsgTime()));
				detail.setOpType("send");
				detail.setHostId(callParam.getUserName());
				MessageDetailCacheManager.getInstance().add(detail);
			}
			TaskManager.taskProcess(callParam);
			_log.info("http response(cfq)2" + respXML);
		} catch (UnsupportedEncodingException e) {
			_log.info("convertResponseString UnsupportedEncodingException error,msg2=" + e.getMessage());
		} catch (IOException e) {
			_log.info("convertResponseString IOException,msg2=" + e.getMessage());
		}
	}

	
	private String convertResponseString(Object answer, int serviceResultCode) {
		_log.info("HBCFQHandle serviceResultCode2 = {}", serviceResultCode);
		String response = "";
		Map<String, String> data = new HashMap<String, String>();
		String[] avpsArr = getAvpsFromMessage(answer);
		_log.info((answer instanceof Message)+"   avpsArr:"+avpsArr);
		if(avpsArr == null ){
			data.put("accNbr", "0");
			data.put("billingCycleId", "0");
			data.put("curFee", "0");
			data.put("sendFee", "0");
			data.put("roamFee", "0");
			data.put("spFee", "0");
			data.put("remark", "");
			data.put("resultCode", "-1");
			data.put("resultMsg", "接口调用异常");
		}else if ((serviceResultCode == 0 && answer instanceof Message) || (avpsArr[2] != null  && answer instanceof XmlMessage)) {
			// 查询成功
			data.put("accNbr", avpsArr[2]);
			data.put("billingCycleId", avpsArr[3]);
			data.put("curFee", avpsArr[4]);
			data.put("sendFee", avpsArr[5]);
			data.put("roamFee", avpsArr[6]);
			data.put("spFee", avpsArr[7]);
			data.put("remark", avpsArr[8] == null ? "" : avpsArr[8]);
			data.put("resultCode", "0");
			data.put("resultMsg", "查询成功");
		} else {
			String resultCode = "-1";
			if ("501".equals(avpsArr[0])) {
				resultCode = "02";
			} else if ("607".equals(avpsArr[0])) {
				resultCode = "03";
			} else if ("608".equals(avpsArr[0])) {
				resultCode = "04";
			} else {
				resultCode = avpsArr[0];
			}

			data.put("accNbr", "0");
			data.put("billingCycleId", "0");
			data.put("curFee", "0");
			data.put("sendFee", "0");
			data.put("roamFee", "0");
			data.put("spFee", "0");
			data.put("remark", avpsArr[8] == null ? "" : avpsArr[8]);
			data.put("resultCode", resultCode);
			data.put("resultMsg", avpsArr[1]);
		}
		// List<Map<String,String>> list = new ArrayList<Map<String,String>>();
		// list.add(data);
		Gson gson = new Gson();
		response = gson.toJson(data);
		return response;
	}

	
	public String[] getAvpsFromMessage(Object answer) {
		String[] avpsArr = new String[11];
		Message answer1=(Message)answer;
		if (answer instanceof Message) {
			AVP avp = answer1.find(Constants.DIAMETER_AVP_SERVICE_INFOMATION, Constants.DIAMETER_VENDOR_3GPP);
			AVP_Grouped avpServiceInfomation;
			if(avp == null){
				return null;
			}
			try {
				avpServiceInfomation = new AVP_Grouped(avp);
				AVP Result = avpServiceInfomation.find(20631, Constants.DIAMETER_VENDOR_CT);
				if (Result != null) {
					avpsArr[0] = String.valueOf(new AVP_Unsigned32(Result).queryValue());
				}

				AVP Para_Field_Result = avpServiceInfomation.find(80407, Constants.DIAMETER_VENDOR_CT);
				if (Para_Field_Result != null) {
					avpsArr[1] = new AVP_UTF8String(Para_Field_Result).queryValue();
				}

				AVP Acc_Nbr = avpServiceInfomation.find(80125, Constants.DIAMETER_VENDOR_CT);
				if (Acc_Nbr != null) {
					avpsArr[2] = new AVP_UTF8String(Acc_Nbr).queryValue();
				}

				AVP BILLING_CYCLE = avpServiceInfomation.find(5043, Constants.DIAMETER_VENDOR_CT);
				if (BILLING_CYCLE != null) {
					avpsArr[3] = new AVP_UTF8String(BILLING_CYCLE).queryValue();
				}

				AVP CurFee = avpServiceInfomation.find(92119, Constants.DIAMETER_VENDOR_CT);
				if (CurFee != null) {
					avpsArr[4] = String.valueOf(new AVP_Unsigned64(CurFee).queryValue());
				}

				AVP SendFee = avpServiceInfomation.find(92120, Constants.DIAMETER_VENDOR_CT);
				if (SendFee != null) {
					avpsArr[5] = String.valueOf(new AVP_Unsigned64(SendFee).queryValue());
				}

				AVP RoamFee = avpServiceInfomation.find(92121, Constants.DIAMETER_VENDOR_CT);
				if (RoamFee != null) {
					avpsArr[6] = String.valueOf(new AVP_Unsigned64(RoamFee).queryValue());
				}

				AVP SpFee = avpServiceInfomation.find(92122, Constants.DIAMETER_VENDOR_CT);
				if (SpFee != null) {
					avpsArr[7] = String.valueOf(new AVP_Unsigned64(SpFee).queryValue());
				}

				AVP Result_desc = avpServiceInfomation.find(92100, Constants.DIAMETER_VENDOR_CT);
				if (Result_desc != null) {
					avpsArr[8] = new AVP_UTF8String(Result_desc).queryValue();
				}
				
			} catch (InvalidAVPLengthException e) {
				e.printStackTrace();
				avpsArr = null;
				_log.error(" getAvpsFromMessage is error when Ne response cca message1");
			}
		}else if (answer instanceof XmlMessage) {
			try {
				XmlMessage xmlMessage=(XmlMessage) answer;
				String data = xmlMessage.getDATA();
				avpsArr[0] = data.substring(data.indexOf("<Result>")+8, data.indexOf("</Result>"));
				avpsArr[1] = data.substring(data.indexOf("<Para_Field_Result>")+19, data.indexOf("</Para_Field_Result>"));
				avpsArr[2] = data.substring(data.indexOf("<Acc_Nbr>")+9, data.indexOf("</Acc_Nbr>"));
				avpsArr[3] = data.substring(data.indexOf("<BILLING_CYCLE>")+15, data.indexOf("</BILLING_CYCLE>"));
				avpsArr[4] = data.substring(data.indexOf("<CurFee>")+8, data.indexOf("</CurFee>"));
				avpsArr[5] = data.substring(data.indexOf("<SendFee>")+9, data.indexOf("</SendFee>"));
				avpsArr[6] = data.substring(data.indexOf("<RoamFee>")+9, data.indexOf("</RoamFee>"));
				avpsArr[7] = data.substring(data.indexOf("<SpFee>"), data.indexOf("</SpFee>"));
				avpsArr[8] = data.substring(data.indexOf("<Result_desc>"+13), data.indexOf("</Result_desc>"));	
			} catch (Exception e) {
				avpsArr = null;
				e.printStackTrace();
				_log.error(" getAvpsFromMessage is error when Ne response cca message2");
			}
			
		}
		
		return avpsArr;
	}

	
	/**
	 * 由于计费侧提供的接口协议没变，只是地址调整，割接到3.0的本地网需要调用新的地址
	 * 集团电子发票API接口调整
	 * 获取判断使用的地址
	 * jf3_flag 刷新开关  配置为1则表示启用割接地市判断，配置为0则表示按现有的流程
	 * Jf3_jt_latn_id  割接地市配置项（多个地市用逗号分隔，如果配置项调整为888，则表示全部调用新地址）
	 * resultLanIdStr 区域编码
	 * 
	 */
	private String getURLForJf3(String jf3_flag,String Jf3_jt_latn_id,String resultLanIdStr) {
		//1 新流程  0 旧的流程
		if("1".equals(jf3_flag)) {
			if("888".equals(Jf3_jt_latn_id)) {
				return "1";
			}else {
				String[] split_jt_latn_id = Jf3_jt_latn_id.split(",");
				for (String string : split_jt_latn_id) {
					if(string.equals(resultLanIdStr)) {
						//包含
						return "1";
					}
				}
			}
			
		}
		return "0";
	}
}
